<template>
  <div class="login-container">
    <div class="login-form">
      <h1>万道发展</h1>
      <form @submit.prevent="handleLogin">
        <div class="form-group">
          <label for="username">用户名</label>
          <input
            id="username"
            v-model="loginForm.username"
            placeholder="请输入用户名"
            required
            :class="{ 'error': errors.username }"
          />
          <span v-if="errors.username" class="error-message">{{ errors.username }}</span>
        </div>

        <div class="form-group">
          <label for="password">密码</label>
          <input
            id="password"
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            required
            :class="{ 'error': errors.password }"
          />
          <span v-if="errors.password" class="error-message">{{ errors.password }}</span>
        </div>

        <div class="form-group">
          <label for="password">验证码</label>
          <div style="display: flex;">
            <img v-if="captcha.image" :src="captcha.image" alt="验证码" style="width: 200px; height: auto;"></img>
            <input
              id="captcha"
              v-model="loginForm.code"
              placeholder="请输入验证码"
              required
              :class="{ 'error': errors.code }"
            />
          </div>
          <span v-if="errors.code" class="error-message">{{ errors.code }}</span>
        </div>


        <br>
        <div class="form-options"  style="display: none;">
          <label class="remember-me">
            <input type="checkbox" v-model="loginForm.rememberMe" />
            记住我
          </label>
          <a href="#" class="forgot-password">忘记密码？</a>
        </div>

        <button type="submit" class="login-btn" :disabled="loading">
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </form>

      <div class="register-link" style="display: none;">
        <span>还没有账号？</span>
        <a href="#" @click.prevent="goToRegister">立即注册</a>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { userApi } from '@/api/user'
import { ElMessage } from 'element-plus'

interface LoginForm {
  username: string
  password: string
  rememberMe: boolean
  code: string
  code_key: string
}

interface Errors {
  username?: string
  password?: string
  code?: string
}

const router = useRouter()
const authStore = useAuthStore()

const loginForm = reactive<LoginForm>({
  username: '',
  password: '',
  rememberMe: false,
  code: '',
  code_key: ''
})

const captcha = ref({
  image:'',
  key: ''
})
const errors = reactive<Errors>({})
const loading = ref(false)

// 表单验证
const validateForm = (): boolean => {
  let isValid = true
  Object.keys(errors).forEach(key => delete errors[key as keyof Errors])

  if (!loginForm.username.trim()) {
    errors.username = '用户名不能为空'
    isValid = false
  } else if (loginForm.username.length < 3) {
    errors.username = '用户名至少3个字符'
    isValid = false
  }

  if (!loginForm.password) {
    errors.password = '密码不能为空'
    isValid = false
  } else if (loginForm.password.length < 6) {
    errors.password = '密码至少6个字符'
    isValid = false
  }

  return isValid
}

// 处理登录
const handleLogin = async () => {
  if (!validateForm()) return
  
  loading.value = true

  try {
    // 模拟登录API调用
    const response = await authStore.login({
      username: loginForm.username,
      password: loginForm.password,
      rememberMe: loginForm.rememberMe,
      code: loginForm.code,
      code_key: loginForm.code_key,
    })
    
    if(response.code==200){
      // 登录成功，跳转到首页或之前访问的页面
      const redirectPath = router.currentRoute.value.query.redirect as string || '/'
      router.push(redirectPath)
    }else{
      ElMessage.error(response.message);
    }

  } catch (error) {
    console.error('登录失败:', error)
  } finally {
    loading.value = false
  }
}

const getCaptcha = async () => {
  try {
    loading.value = true;
    const response = await userApi.getCaptcha();
    captcha.value = { image: response.data.image||'',key: response.data.key };
    loginForm.code_key = response.data.key;
  } catch (error) {
    console.error('获取用户数据失败:', error);
  } finally {
    loading.value = false;
  }
};
getCaptcha()


const goToRegister = () => {
  router.push('/register')
}
</script>

<style scoped>

.login-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(180deg, #4F97F4 0%, #CEE6FD 53%);
  padding: 0px;
}

.login-form {
  background: white;
  padding: 40px;
  border-radius: 10px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  width: 100%;
  max-width: 400px;
}

.login-form h1 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-size: 24px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #555;
  font-weight: 500;
}

.form-group input {
  width: 100%;
  padding: 12px;
  border: 2px solid #e1e5e9;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-group input:focus {
  outline: none;
  border-color: #4F97F4;
}

.form-group input.error {
  border-color: #e74c3c;
}

.error-message {
  color: #e74c3c;
  font-size: 12px;
  margin-top: 5px;
  display: block;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.remember-me {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #555;
  font-size: 14px;
}

.forgot-password {
  color: #4F97F4;
  text-decoration: none;
  font-size: 14px;
}

.forgot-password:hover {
  text-decoration: underline;
}

.login-btn {
  width: 100%;
  padding: 12px;
  background: #4F97F4;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.3s;
}

.login-btn:hover:not(:disabled) {
  background: #5a6fd8;
}

.login-btn:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
}

.register-link {
  text-align: center;
  margin-top: 20px;
  color: #555;
}

.register-link a {
  color: #4F97F4;
  text-decoration: none;
  margin-left: 5px;
}

.register-link a:hover {
  text-decoration: underline;
}
</style>